<template>
  <div>
    <div class="wallet-banner linear-bg-blue">
      <h1 class="big-amount">{{balance}}</h1>
      <h1 class="small-amount">点数：{{pointNum}}</h1>
      <p class="action">
        <span>帐户余额</span>
        <span class="icon" @click="handleCharge">充值</span>
        <span class="icon" @click="handleTransfer">转账至云帐户</span>
      </p>
    </div>
    <div class="list">
      <i-tabs :current="activeType" color="#6692f7" @change="handleTabChange">
        <i-tab v-for="item in transType" :key="item.key" :title="item.name"></i-tab>
      </i-tabs>
      <div class="list-title" style="height:35px">
        <span class="col">内容</span>
        <span class="col">金额</span>
        <span class="col">点数</span>
        <span class="col">时间</span>
      </div>
      <scroll-view
        class="scroll-wrap no-scroll-bar"
        style="height:calc(100% - 42px - 36px)"
        scroll-y
        @scrolltolower="handleLoadMore"
      >
        <div v-for="(item,idx) in list" :key="idx" class="info-block">
          <span class="col ellipsis-2">{{item.content}}</span>
          <span class="col ellipsis-2">{{item.amount}}</span>
          <span class="col ellipsis-2">{{item.point}}</span>
          <span class="col ellipsis-2">{{item.createDate}}</span>
        </div>
        <p v-if="alreadyLastPage" class="end-tip">没有更多了</p>
      </scroll-view>
    </div>

    <div class="popup-window" :class="{show:showPopup}">
      <span class="close-icon" @click="handleHide">&times;</span>
      <div v-if="!qrURL&&!isTransfer" key="1" class="popup-wrap">
        <input
          v-model="orderAmount"
          class="input-block"
          type="digit"
          placeholder="请输入充值金额"
          placeholder-class="placeholder-part"
        />
        <div class="popup-btn-wrap">
          <span class="cancel-btn" @click="handleHide">取消</span>
          <span class="confirm-btn" @click="chargeAccount">确定</span>
        </div>
      </div>
      <div v-else-if="isTransfer" key="2" class="popup-wrap">
        <input
          v-model="orderAmount"
          class="input-block"
          type="digit"
          placeholder="请输入转账金额"
          placeholder-class="placeholder-part"
        />
        <div class="popup-btn-wrap">
          <span class="cancel-btn" @click="handleHide">取消</span>
          <span class="confirm-btn" @click="transferToCloudAccount">确定</span>
        </div>
      </div>
      <div v-else key="3" class="qr-wrap">
        <img :src="qrURL" mode="aspectFit" class="qr-code" />
        <p class="tip">请识别二维码进行支付</p>
        <button class="btn-color-blue" @click="scanPayOrder">我已完成支付</button>
      </div>
    </div>
  </div>
</template>

<script>
import {} from '@/utils'
import {
  FIND_SHOP_BASE_INFO,
  FIND_SHOP_BUSINESS_LOG_PAGE,
  CHARGE_ACCOUNT,
  FIND_CHARGE_ACCOUNT_ORDER,
  FIND_TRANSFER_TO_CLOUD_ACCOUNT_TAX,
  TRANSFER_TO_CLOUD_ACCOUNT
} from '@/api'

export default {
  components: {},
  props: {},
  data () {
    return {
      freeAssets: '',
      pointNum: '',
      currentPage: 1,
      activeType: '0',
      transType: [
        { key: '0', name: '余额类型' },
        { key: '1', name: '反佣类型' },
        { key: '2', name: '积分类型' }
      ],
      logList: [],
      alreadyLastPage: false,
      showPopup: false,
      orderAmount: '',
      orderNum: '',
      qrURL: '',
      isTransfer: false,
      transferSuccess: false
    }
  },
  computed: {
    account () {
      return this.$store.state.account
    },
    balance () {
      if (this.freeAssets || this.freeAssets === 0) {
        return '￥' + (this.freeAssets * 0.01).toFixed(2)
      } else {
        return ''
      }
    },
    list () {
      return this.logList.map(_ => ({
        amount: '￥' + (_.amount * 0.01).toFixed(2),
        content: _.content,
        createDate: _.createDate,
        point: _.point || ''
      }))
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onShow () {
    this.getShopBaseInfo()
    this.getTransLog()
  },
  methods: {
    handleTabChange (e) {
      let key = e.target.key
      this.activeType = key

      this.currentPage = 1
      this.getTransLog()
    },
    handleCharge () {
      this.isTransfer = false
      this.showPopup = true
    },
    handleTransfer () {
      this.isTransfer = true
      this.showPopup = true
    },
    handleLoadMore () {
      if (!this.alreadyLastPage) {
        this.getTransLog()
      }
    },
    handleHide () {
      const vm = this
      vm.showPopup = false
      setTimeout(() => {
        if (vm.orderNum || vm.transferSuccess) {
          vm.getShopBaseInfo()
        }

        vm.orderAmount = ''
        vm.orderNum = ''
        vm.qrURL = ''
        vm.isTransfer = false
        vm.transferSuccess = false
      }, 300)
    },

    getShopBaseInfo () {
      const vm = this

      FIND_SHOP_BASE_INFO(vm.account.shopId)
        .then(r => {
          if (r.data.code === '0') {
            vm.pointNum = r.data.data.point
            vm.freeAssets = r.data.data.freeAssets
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    getTransLog () {
      const vm = this

      let params = {
        shopId: vm.account.shopId,
        transType: vm.activeType
      }

      FIND_SHOP_BUSINESS_LOG_PAGE(params, vm.currentPage, 10)
        .then(r => {
          if (r.data.code === '0') {
            let { list, isFirstPage, isLastPage } = r.data.data
            vm.printList(list, isFirstPage, isLastPage)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    printList (list, isFirst, isLast) {
      if (isFirst) {
        this.logList = list
        if (isLast || !list.length) {
          // only one page
          this.alreadyLastPage = true
        } else {
          // has next page
          this.alreadyLastPage = false
          this.currentPage += 1
        }
      } else if (isLast) {
        // more than one page and this is the last page
        this.logList.push(...list)
        this.alreadyLastPage = true
      } else {
        // middle page
        this.logList.push(...list)
        this.alreadyLastPage = false
        this.currentPage += 1
      }
    },
    chargeAccount () {
      const vm = this

      if (!vm.orderAmount) {
        vm.$toast('请输入充值金额')
        return false
      }

      let params = {
        amount: vm.orderAmount * 1,
        providerId: vm.account.providerId,
        relateMan: vm.account.shopId,
        storeIdentityEnum: 'SHOP',
        payMethodEnum: 'MINI', // 之前是改了的WECHAT
        paySourceEnum: 'H5' // 之前是改了的MINI
      }

      CHARGE_ACCOUNT(params)
        .then(r => {
          if (r.data.code === '0') {
            vm.qrURL = 'data:image/png;base64,' + r.data.data.data
            vm.orderNum = r.data.data.orderNum
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {})
    },
    scanPayOrder () {
      const vm = this

      FIND_CHARGE_ACCOUNT_ORDER(vm.orderNum)
        .then(r => {
          if (r.data.code === '0') {
            if (r.data.data && r.data.data.state) {
              // charge success
            } else {
              vm.$toast('支付信息未找到，请稍后再试')
            }
            setTimeout(() => {
              vm.handleHide()
            }, 300)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    transferToCloudAccount () {
      const vm = this

      if (!vm.orderAmount) {
        vm.$toast('请输入转账金额')
        return false
      }

      let params = {
        identity: 'SHOP',
        orderAmount: vm.orderAmount * 100,
        relateMan: vm.account.shopId
      }

      FIND_TRANSFER_TO_CLOUD_ACCOUNT_TAX(params)
        .then(r => {
          if (r.data.code === '0') {
            vm.confirmTransfer(r.data.data)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    confirmTransfer (obj) {
      const vm = this

      vm
        .$dialog(
          `实际到账${obj.amount * 0.01}元，税率${obj.withdrawTaxRatio *
            100}%，是否要转账？`
        )
        .then(r => {
          vm.startTransfer()
        })
        .catch(e => {
          // cancel
          // do nothing
        })
    },
    startTransfer () {
      const vm = this

      let params = {
        identity: 'SHOP',
        orderAmount: vm.orderAmount * 100,
        relateMan: vm.account.shopId
      }

      TRANSFER_TO_CLOUD_ACCOUNT(params)
        .then(r => {
          if (r.data.code === '0') {
            vm.transferSuccess = true
            vm.$toast('操作成功')
            vm.handleHide()
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'static/styles/color.scss';

.list {
  height: calc(100% - 120px);
  > .list-title {
    padding: 0 15px;
    font-size: 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid $light-gray;
    > .col {
      color: $gray;
      width: 25%;
      text-align: center;
    }
  }
  > .scroll-wrap {
    box-sizing: border-box;
    padding: 0 15px;
    .info-block {
      font-size: 14px;
      padding: 10px 0;
      border-bottom: 1px solid $light-gray;
      display: flex;
      justify-content: space-between;
      align-items: center;
      > .col {
        width: 25%;
        text-align: center;
      }
    }
    .end-tip {
      margin: 0;
      padding: 15px;
      text-align: center;
      color: $gray;
      font-size: 15px;
    }
  }
}
.popup-window {
  display: flex;
  justify-content: center;
  align-items: center;
  > .popup-wrap,
  > .qr-wrap {
    background-color: $white;
    width: 280px;
    border-radius: 8px;
    padding: 15px 15px 60px;
    position: relative;
    overflow: hidden;
    > .input-block {
      width: calc(100% - 20px);
      padding: 5px 10px;
      font-size: 15px;
      border: 1px solid $light-gray;
      border-radius: 4px;
    }
    > .popup-btn-wrap {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1px solid $light-gray;
      > .cancel-btn,
      > .confirm-btn {
        width: 50%;
        height: 40px;
        line-height: 40px;
        font-size: 15px;
        text-align: center;
        background-color: $white;
        &.confirm-btn {
          color: $blue;
          border-left: 1px solid $light-gray;
        }
      }
    }
  }
  > .qr-wrap {
    > .qr-code {
      width: 250px;
      height: 250px;
    }
    > .tip {
      font-size: 12px;
      color: $blue;
      text-align: center;
    }
    > .btn-color-blue {
      position: absolute;
      bottom: 20px;
      left: 15px;
      width: calc(100% - 30px);
    }
  }
}
</style>
